<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="SKU编码" prop="sku">
        <el-input
          v-model="queryParams.sku"
          placeholder="请输入SKU编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属店铺" prop="shopId">
        <el-select v-model="queryParams.shopId" placeholder="请选择店铺" clearable>
          <el-option
            v-for="item in shopOptions"
            :key="item.shopId"
            :label="item.shopName"
            :value="item.shopId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="财务时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['profit:aftersale:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['profit:aftersale:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['profit:aftersale:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['profit:aftersale:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="aftersaleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="SKU编码" align="center" prop="sku" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="SKU货号" align="center" prop="skuCode" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="产品名称" align="center" prop="productName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="SKU属性" align="center" prop="skuAttr" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="售后金额" align="center" prop="aftersaleAmount" width="120">
        <template slot-scope="scope">
          <span style="color: #F56C6C; font-weight: bold;">{{ scope.row.aftersaleAmount != null ? '¥' + scope.row.aftersaleAmount : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="财务时间" align="center" prop="arrivalDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.arrivalDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属店铺" align="center" prop="shopName" width="120" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['profit:aftersale:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['profit:aftersale:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改售后明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="SKU编码" prop="sku">
              <el-input v-model="form.sku" placeholder="请输入SKU编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="SKU属性" prop="skuAttr">
              <el-input v-model="form.skuAttr" placeholder="请输入SKU属性" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售后金额" prop="aftersaleAmount">
              <el-input-number v-model="form.aftersaleAmount" :precision="2" :min="0" :max="9999999" placeholder="请输入售后金额" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="财务时间" prop="arrivalDate">
              <el-date-picker
                v-model="form.arrivalDate"
                type="datetime"
                placeholder="选择财务时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属店铺" prop="shopId">
              <el-select v-model="form.shopId" placeholder="请选择店铺" style="width: 100%">
                <el-option
                  v-for="item in shopOptions"
                  :key="item.shopId"
                  :label="item.shopName"
                  :value="item.shopId"
                  :disabled="item.status == '1'"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="500px" append-to-body center>
      <el-form label-width="100px">
        <el-form-item label="所属店铺" required>
          <el-select v-model="upload.shopId" placeholder="请选择店铺" style="width: 100%">
            <el-option
              v-for="shop in shopOptions"
              :key="shop.shopId"
              :label="shop.shopName"
              :value="shop.shopId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="display: flex; justify-content: center;">
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport + '&shopId=' + upload.shopId"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :auto-upload="false"
          drag
          style="text-align: center;"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。系统将自动识别"结算-消费者退款金额"和"消费者及履约保障-售后问题"两个sheet页。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading" :disabled="upload.isUploading">
          {{ upload.isUploading ? '导入中...' : '确 定' }}
        </el-button>
        <el-button @click="upload.open = false" :disabled="upload.isUploading">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAftersale, getAftersale, delAftersale, addAftersale, updateAftersale } from "@/api/business/profit"
import { getShopList } from "@/api/system/user"
import { getToken } from "@/utils/auth"

export default {
  name: "ProfitAftersale",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 售后明细表格数据
      aftersaleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 店铺选项
      shopOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sku: null,
        productName: null,
        shopId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sku: [
          { required: true, message: "SKU编码不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        aftersaleAmount: [
          { required: true, message: "售后金额不能为空", trigger: "blur" }
        ],
        arrivalDate: [
          { required: true, message: "财务时间不能为空", trigger: "change" }
        ],
        shopId: [
          { required: true, message: "所属店铺不能为空", trigger: "change" }
        ]
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 所属店铺ID
        shopId: null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/profit/aftersale/importData"
      }
    }
  },
  created() {
    this.getList()
    this.getShopOptions()
  },
  methods: {
    /** 查询售后明细列表 */
    getList() {
      this.loading = true
      listAftersale(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.aftersaleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取店铺选项 */
    getShopOptions() {
      getShopList().then(response => {
        this.shopOptions = response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        aftersaleId: null,
        sku: null,
        productName: null,
        skuAttr: null,
        aftersaleAmount: null,
        arrivalDate: null,
        shopId: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.aftersaleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加售后明细"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const aftersaleId = row.aftersaleId || this.ids
      getAftersale(aftersaleId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改售后明细"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.aftersaleId != null) {
            updateAftersale(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAftersale(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const aftersaleIds = row.aftersaleId || this.ids
      this.$modal.confirm('是否确认删除选中的售后明细？').then(function() {
        return delAftersale(aftersaleIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "售后明细导入"
      this.upload.shopId = null
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('business/profit/aftersale/importTemplate', {
      }, `售后明细导入模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
      // 显示加载提示
      this.$message({
        message: '正在导入数据，请稍候...',
        type: 'info',
        duration: 0,
        customClass: 'upload-loading-message'
      })
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      // 关闭所有消息提示
      this.$message.closeAll()
      // 显示导入结果
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 文件上传失败处理
    handleFileError(err, file, fileList) {
      this.upload.isUploading = false
      this.$message.closeAll()
      this.$modal.msgError("导入失败，请重试")
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.upload.shopId) {
        this.$modal.msgError("请选择所属店铺")
        return
      }
      if (this.upload.isUploading) {
        this.$modal.msgWarning("正在导入中，请勿重复提交")
        return
      }
      this.$refs.upload.submit()
    }
  }
}
</script>

